package leetcode;

public class _14_LongestCommonPrefix {
    class Solution {
        public String longestCommonPrefix(String[] strs) {
            StringBuilder res = new StringBuilder("");
            if (strs.length == 0 || strs[0].equals("")) {//如果strs是空数组或者strs只包含一个空字符串元素，直接返回""
                return String.valueOf(res);
            }
            if (strs.length == 1) {//如果strs只包含一个非空元素，则直接返回改元素
                return strs[0];
            }
            int index = 0;//记录每个字符串的下标位置
            while (index != -1) {//判断strs中字符串的共同前缀
                if (index == strs[1].length()) {
                    return String.valueOf(res);
                }//如果index的长度达到了第一个字符串的长度，则结束
                Character indexChar = strs[1].charAt(index);
                for (String item : //依次遍历strs中的每个字符串，以第一个字符串中元素indexChar为标准，比较是否相同，有一个不同则结束遍历
                        strs) {
                    if (index == item.length() || item.charAt(index) != indexChar) {
                        return String.valueOf(res);
                    }
                }
                res.append(indexChar);
                index++;
            }
            return String.valueOf(res);
        }
    }

    Solution getSolution() {
        return new Solution();
    }

    public static void main(String[] args) {
        _14_LongestCommonPrefix c = new _14_LongestCommonPrefix();
        _14_LongestCommonPrefix.Solution s = c.getSolution();
        String[] strs = {"flower", "flow", "flight"};
        String[] strs2 = {"dog", "racecar", "car"};
        String[] strs3 = {""};
        String res = s.longestCommonPrefix(strs3);
        System.out.println(res);
    }
}
